package com.mk.web.threadpool;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by WangChen on 2018/12/15 7:46.
 */
public class ThreadState {


    // ctl这是一个很重要的参数，使用位标记方式，将当前线程池状态和当前线程池创建的任务多少杂糅到了一起
    private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
    // 预留三位
    private static final int COUNT_BITS = Integer.SIZE - 3;// 29
    // 线程池最大线程大小：(2^29)-1 (about 500 million)
    private static final int CAPACITY   = (1 << COUNT_BITS) - 1;// 00011111111111111111111111111111

    // 线程池状态位，使用int的高三位进行储存
    private static final int RUNNING    = -1 << COUNT_BITS;// 11100000000000000000000000000000
    private static final int SHUTDOWN   =  0 << COUNT_BITS;// 00000000000000000000000000000000
    private static final int STOP       =  1 << COUNT_BITS;// 00100000000000000000000000000000
    private static final int TIDYING    =  2 << COUNT_BITS;// 01000000000000000000000000000000
    private static final int TERMINATED =  3 << COUNT_BITS;// 01100000000000000000000000000000

    public static void main(String [] args){

        System.out.println(to32BitBinary((1 << COUNT_BITS)));// 00100000000000000000000000000000

        // =================================================================
        // 线程池状态位，使用int的高三位进行储存
//        int RUNNING    = -1 << COUNT_BITS;// 11100000000000000000000000000000
        System.out.println(RUNNING);
        System.out.println(Integer.toBinaryString(RUNNING));

//        int SHUTDOWN   =  0 << COUNT_BITS;// 00000000000000000000000000000000
        System.out.println(SHUTDOWN);
        System.out.println(to32BitBinary(SHUTDOWN));

//        int STOP       =  1 << COUNT_BITS;// 00100000000000000000000000000000
        System.out.println(STOP);
        System.out.println(to32BitBinary(STOP));

//        int TIDYING    =  2 << COUNT_BITS;// 01000000000000000000000000000000
        System.out.println(TIDYING);
        System.out.println(to32BitBinary(TIDYING));

//        int TERMINATED =  3 << COUNT_BITS;// 01100000000000000000000000000000
        System.out.println(TERMINATED);
        System.out.println(to32BitBinary(TERMINATED));
        // =================================================================
    }

    // 通过ctl值计算出运行线程池状态值
    private static int runStateOf(int c)     { return c & ~CAPACITY; } // 位取反 所有位包括符号位均取反
    // 通过ctl值计算出线程池当前任务多少的值
    private static int workerCountOf(int c)  { return c & CAPACITY; }  // 位与运算 全为1才为1
    // 通过运行状态和任务多少的两个值，生成ctl这个包装的值
    private static int ctlOf(int rs, int wc) { return rs | wc; }       // 位或运算 全为0才为0


    static String to32BitBinary(int i){
        return String
                .format("%32s", Integer.toBinaryString(i))
                .replace(' ', '0');
    }
}
